import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_SERVER_URL,
  withCredentials: false, // send cookies when cross-domain requests
  // crossDomain: true,
  timeout: 15000 // request timeout
})

// request interceptor 请求拦截
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['x-morefunoa-access-token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor 响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.success) {
      return res
    } else {
      Message({
        message: res.errorMessage || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      const tokenError = new RegExp('^600[0-9]{2}$')
      if (tokenError.test(res.errorCode)) { // token异常判断
        MessageBox.confirm(
          '退出重新登录',
          '确认登出',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.errorMessage || 'Error'))
    }
  },
  error => {
    Message({
      message: error.message ,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
